<?php

namespace app\api\controller;

use app\api\controller\Auth;
use app\api\model\Token;
use app\api\model\User as userModel;
use app\common\controller\ApiController;
use app\Request;
use Icharle\Wxtool\Wxtool;
use think\App;
use think\facade\Db;
use think\facade\Log;

class User extends ApiController
{
    protected $noNeedLogin = ['wx_login','getopenid','getphone',"wx_newlogin"];
    /**
     * 登录
     * @return string
     * @throws \Exception
     */
    public function wx_login(userModel $user)
    {
        $param = $this->request->param();
       
        $wx = new Wxtool();
        if (empty($param['code'])) {
            $this->error("参数有误");
        }
        // if (empty($param['code']) || empty($param['encryptedData']) || empty($param['iv'])) {
        //     $this->error("参数有误");
        // }
        $code = $param['code'];
        // $encryptedData = urldecode($param['encryptedData']);
        // $iv = urldecode($param['iv']);
        $res = $wx->GetSessionKey($code);

        $nickName = nickname();
        $avatarUrl = "https://ls.yquewx.com/upload/login.jpg";

        $openId = $res['openid'];
      //  $unionId = empty($res['unionid']) ? '' : $res['unionid'];
        $isExit = $user->where('wx_openid', $openId)->find();
        //'unionId' => $unionId,   "nickname" => $nickName, 
        $saveData = ['update_time' => time(), 'avatar' => $avatarUrl];
        if (!empty($isExit)) {
            $uid = $isExit['id'];
            $ret = $user->where('id', $uid)->update($saveData);
            $gender = $isExit["gender"];
            $nickName = $isExit["nickname"];
        } else {
            $user = new userModel();
            $saveData['wx_openid'] = $openId;
            $saveData['nickname'] = $nickName;
            $ret = $user->save($saveData);
            $uid = $user->id;
            $gender = $user->gender;
        }  
        if ($ret) {
            $token = Auth::makeToken();
            $userToken = new Token();
            $userToken->setToken($token, $uid, $this->method);
            $user_info = ['nickname' => $nickName, 'avatar' => $avatarUrl,"uid"=>$uid,"gender"=>$gender];
            $this->success('登录成功', ['token' => $token, 'method' => $this->method, 'user_info' => $user_info]);
        } else {
            $this->error('登陆失败,请稍后重试001');
        }
    }


    public function getopenid(){
        $param = $this->request->param();
        $wx = new Wxtool();
        if (empty($param['code'])) {
            $this->error("参数有误");
        }
        $code = $param['code'];
        $res = $wx->GetSessionKey($code);
        $this->success('登录成功', $res);
    }

    public function getphone(userModel $user){
        $param = $this->request->param();
        $wx = new Wxtool();
        // if (empty($param['session_key']) || empty($param['encryptedData']) || empty($param['iv']) || empty($param['openid'])) {
        //     $this->error("参数有误");
        // }
        if (empty($param['code']) || empty($param['encryptedData']) || empty($param['iv'])) {
            $this->error("参数有误");
        }
        $code = $param['code'];
        $res = $wx->GetSessionKey($code);
       
        $encryptedData = urldecode($param['encryptedData']);
        $iv = urldecode($param['iv']);
        $userinfo = $wx->GetUserInfo($encryptedData, $iv,$res['session_key']);
        $userinfo = json_decode($userinfo, true);
        $openId = $res['openid'];
        $phone = empty($userinfo['phoneNumber']) ? '' : $userinfo['phoneNumber'];
        //dump($phone);die;
        //'unionId' => $unionId,
        //$unionId = empty($param['unionid']) ? '' : $param['unionid'];
        $nickName = nickname();
        $avatarUrl = "https://ls.yquewx.com/upload/login.jpg";
        $isExit = $user->where('wx_openid', $openId)->find();
        $saveData = [ 'update_time' => time(), 'gender' => 0, 'avatar' => $avatarUrl,'phone' => $phone];
        if (!empty($isExit)) {
            $uid = $isExit['id'];
            $ret = $user->where('id', $uid)->update($saveData);
            $nickName = $isExit["nickname"];
            
        }else {
            $user = new userModel();
            $saveData['wx_openid'] = $openId;
            $saveData['nickname'] = $nickName;
            $ret = $user->save($saveData);
            $uid = $user->id;
        }
        // file_put_contents('wx.log', "ret:" . $ret . PHP_EOL, FILE_APPEND);
        if ($ret) {
            $token = Auth::makeToken();
            $userToken = new Token();
            $userToken->setToken($token, $uid, $this->method);
            $user_info = ['nickname' => $nickName, 'phone' => $phone,'avatar' => $avatarUrl,"uid"=>$uid];
            $this->success('登录成功', ['token' => $token, 'method' => $this->method, 'user_info' => $user_info]);
        } else {
            $this->error('登陆失败，请稍后重试1');
        }
       
    }



      //H5微信用户授权登录
      public function wx_newlogin(userModel $user)
      {
          $param = $this->request->param();
          if (empty($param['code'])) {
              $this->error("参数有误");
          }
          $accop = $this->get_access_token_openid($param['code']);
         
          $userinfo = $this->get_userinfoarea($accop["access_token"],$accop["openid"]);
         
          $isExit = $user->where('wx_openid', $userinfo['openid'])->find();
          $saveData = ['nickname' => $userinfo['nickname'],'gender' => $userinfo['sex'],'avatar' => $userinfo['headimgurl'],"wx_openid"=>$userinfo["openid"]];
          if (!empty($isExit)) {
              $uid = $isExit['id'];
              $ret = $user->where('id', $uid)->update($saveData);
              $gender = $isExit["gender"];
              $nickName = $isExit["nickname"];
              $avatarUrl = $isExit["avatar"];
          } else {
              $user = new userModel();
              $ret = $user->save($saveData);
              $uid = $user->id;
              $gender = $user->gender;
              $avatarUrl = $user->avatar;
              $nickName = $user->nickname;
          }  
          if ($ret) {
              $token = Auth::makeToken();
              $userToken = new Token();
              $userToken->setToken($token, $uid, $this->method);
              $user_info = ['nickname' => $nickName, 'avatar' => $avatarUrl,"uid"=>$uid,"gender"=>$gender];
              $this->success('登录成功', ['token' => $token, 'method' => $this->method, 'user_info' => $user_info]);
          } else {
              $this->error('登陆失败,请稍后重试');
          }
      }
  
      //获取access_token和openid
      public function get_access_token_openid($code){
          $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxe2943a6ef9364385&secret=8c877d24139000d6ca2274dee731ca5d&code=".$code."&grant_type=authorization_code";
          $result = Curl::get($url);
          $data = json_decode($result, true);
     
          return [
              "access_token"=>$data["access_token"],
              "openid"=>$data["openid"],
          ];
  
      }
  
      //获取用户信息
      public function get_userinfoarea($access_token,$openid){
   
          $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
          $result = Curl::get($url);
          $data = json_decode($result, true);
          return [
              "openid"=>$data["openid"],
              "nickname"=>$data["nickname"],
              "sex"=>$data["sex"],
              "headimgurl"=>$data["headimgurl"]
          ];
      }






     


}
